package com.jfinal.weixin.controller;

import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.model.MbUser;
import com.jfinal.weixin.model.MbVote;
import com.jfinal.weixin.model.WeixinInfo;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import com.jfinal.weixin.sdk.api.UserApi;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by 446705260@qq.com on 16/5/21.
 * chengzhichao
 */
public class VoteController extends Controller {
    // 单个用户每日为每个用户帮砍次数
    private static int DAILYCUT = 1;
    // 单个用户每日总砍价次数
    private static int DAILYALLCUT = 3;
    // 单个用户总砍价次数
    private static int ALLCUT = 999999;

    private static int JIANXI = 0;
    public ApiConfig getApiConfig() {
        ApiConfig ac = new ApiConfig(WeixinInfo.dao.getWeixinInfoById(1));
        return ac;
    }
    public void index() {
        int pageNumber = getParaToInt("pageNumber", 1);
        int sort = getParaToInt("sort", 0);
        String keyword = getPara("keyword", null);
        String sql = "from mbuser where 1 = 1";
        Page<Record> userPage;
        if (keyword != null) {
            sql = sql + " and name = '" + keyword + "' or id ='" + keyword+"'";
            userPage = Db.paginate(pageNumber, 10, "select *", sql);
        } else {
            if(sort==1){
                sql = sql + " order by curscore desc";
            }
            userPage = Db.paginate(pageNumber, 10, "select *", sql);
        }

        setAttr("userPage", userPage);
        Map paraMap = JsTicketApi.makeSignature(getRequest(), this.getApiConfig());
        paraMap.put("sharetitle","好多红安的宝宝都在参加红安红萌宝大赛,赶紧来吧");
        paraMap.put("shareimg","http://img0.fumuhui.com/20121210/1/2012121007345315640.jpg");
        paraMap.put("sharedesc","叔叔阿姨来帮我一下吧,拿奖品呢!");
        paraMap.put("sharesuccess","分享成功,关注红安红和红安人都可以投票哦");
        paraMap.put("sharefail","分享失败,关注红安红和红安人都可以投票哦");
        setAttr("map", paraMap);
        setAttr("alluser",MbUser.dao.getalluser());
        setAttr("allvote",MbVote.dao.getallvote());
        render("index.html");
    }

    public void personal(){
        int id = getParaToInt("babyid",0);
        MbUser mbUser = MbUser.dao.findById(id);
        if (mbUser==null||mbUser.getStr("name").equals("")){
            renderHtml("<h1>用户不存在</h1>");
        }else {
            setAttr("user",mbUser);
            setAttr("position",mbUser.getbiger(mbUser.getInt("curscore"))+1);
            Map paraMap = JsTicketApi.makeSignature(getRequest(), this.getApiConfig());
            paraMap.put("sharetitle","亲亲宝宝"+mbUser.get("name","未知用户")+"正在参加红安红萌宝大赛,帮我一下咯");
            paraMap.put("shareimg","http://bbs.0713hah.com/cdn/img/"+mbUser.get("imgurl","mb01")+".jpg");
            paraMap.put("sharedesc","叔叔阿姨来帮我一下吧,拿奖品呢!");
            paraMap.put("sharesuccess","分享成功,关注红安红和红安人都可以投票哦");
            paraMap.put("sharefail","分享失败,关注红安红和红安人都可以投票哦");
            setAttr("alluser",MbUser.dao.getalluser());
            setAttr("allvote",MbVote.dao.getallvote());
            setAttr("map", paraMap);
        }

        render("personal.html");
    }


    public String dovote(int userid,String openid){
        String result="";

        if(false){
            result="该用户投票期已过";
        }else{
            MbUser user = MbUser.dao.findById(userid);
            if (user == null) {
                return "查无此人或者活动已结束";
            }
            if (MbVote.dao.gettodayall(openid, userid) >= DAILYCUT
                    || MbVote.dao.gettodayall(openid) >= DAILYALLCUT
//                    || MbVote.dao.getthism(userid) >= JIANXI
                    || MbVote.dao.getAllCut(openid) >= ALLCUT
                    ) {
                if (MbVote.dao.gettodayall(openid, userid) >= DAILYCUT) {
                    result = ("您已经给该宝贝投过了");
                    return result;
                }

                if (MbVote.dao.gettodayall(openid) >= DAILYALLCUT) {
                    result = ("每日最多3票哦");
                    return result;
                }

                if (MbVote.dao.getAllCut(openid) >= ALLCUT) {
                    result = ("您已经投票过了");
                    return result;
                }

//                if (MbVote.dao.getthism(userid) >= JIANXI) {
//                    result = ("该用户太火爆，请稍后再试.");
//                    return result;
//                }


            } else {
                Date now = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String nowtime = sdf.format(now);
                MbVote cut = new MbVote();
                ApiResult ar = UserApi.getUserInfo(openid);
                String city = ar.get("city");
                String nickname = ar.get("nickname");
                int curscore = cut.getScoreOfSomeOne(userid);
                cut.set("secno", openid).set("ctime", nowtime).set("city",city)
                        .set("nickname", nickname).set("userid", userid).set("statu", 0).set("curscore", (curscore+1));
                if (cut.save()) {
//                    String yzm = "2016"+cut.getInt("id");
//                    int a  =Integer.parseInt(yzm);
//                    java.util.Random random=new java.util.Random();// 定义随机类
//                    int b=random.nextInt(10)+1;// 返回[0,10)集合中的整数，注意不包括10
//                    int c = a-b;
                    //result="请输入计算结果:\n【"+c+"+"+b+"等于几？】\n完成给"+user.getStr("name")+"的投票";

                    user.set("curscore",cut.getInt("curscore")).update();
                    result = "投票成功；"+user.getStr("name")+"已增长一票.关注红安红也可以投一票哦,感谢您的参与!";

                } else {
                    result = ("投票失败");
                }

            }
        }



        return result;
    }

    public String revote(String openid,int id){
        String result="";
        MbVote vote = MbVote.dao.findById(id);
        if(vote!=null){
            if(openid.equals(vote.getStr("secno"))){
                if(vote.getInt("statu")!=0){
                    vote.set("statu",0).update();
                    MbUser mbUser = MbUser.dao
                            .findById(vote.getInt("userid"));
                    mbUser.set("curscore",mbUser.getInt("curscore")+1).update();
                    result = ("投票成功；"+mbUser.getStr("name")+"已增长一票.关注红安红也可以投一票哦,感谢您的参与！");
                }else{
                    result = ("验证码错误或已失效");
                }
            }else{
                result = ("回答错误，请重新计算验证码!");
            }
        }else{
            result = ("验证码错误或已失效");
        }

        return result;
    }
}
